<template>
  <a-card
    :bordered="false"
    class="search-wrapper"
    :style="{ 'margin-bottom': list.length > 2 * columnNum ? '54px' : '24px' }"
  >
    <a-spin :spinning="loading">
      <div class="serch-header">
        <slot name="header"></slot>
      </div>
      <a-form v-bind="$attrs" labelAlign="right" :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-row :gutter="16" type="flex">
          <template v-for="(item, index) in list">
            <a-col :span="24 / columnNum" v-if="index < 2 * columnNum" :key="index">
              <a-form-item :label="item.label">
                <span v-if="item.extra" slot="extra" class="extra">温馨提示：{{ item.extra }}</span>
                <template v-if="item.slot">
                  <slot :name="item.slot"></slot>
                </template>
                <template v-else>
                  <component
                    :is="componentType(item.type)"
                    :allowClear="handleAllowClear(item)"
                    autocomplete="off"
                    @pressEnter="handleSearch"
                    v-bind="item.props"
                    v-on="item.methods"
                    v-decorator="[
                      item.fields,
                      {
                        rules: item.validate,
                        initialValue: item.initialValue || undefined,
                        valuePropName: item.type === 'switch' ? 'checked' : 'value',
                      },
                    ]"
                  ></component>
                </template>
              </a-form-item>
            </a-col>
          </template>
          <collapseTransition v-if="list.length > 2 * columnNum">
            <div v-show="showMore" style="width: 100%">
              <template v-for="(item, index) in list">
                <a-col :span="24 / columnNum" v-if="index >= 2 * columnNum" :key="index">
                  <a-form-item :label="item.label">
                    <span v-if="item.extra" slot="extra" class="extra">温馨提示：{{ item.extra }}</span>
                    <template v-if="item.slot">
                      <slot :name="item.slot"></slot>
                    </template>
                    <template v-else>
                      <component
                        :is="componentType(item.type)"
                        :allowClear="handleAllowClear(item)"
                        autocomplete="off"
                        v-on="item.methods"
                        v-bind="item.props"
                        v-decorator="[
                          item.fields,
                          {
                            rules: item.validate,
                            initialValue: item.initialValue || undefined,
                            valuePropName: item.type === 'switch' ? 'checked' : 'value',
                          },
                        ]"
                      ></component>
                    </template>
                  </a-form-item>
                </a-col>
              </template>
            </div>
          </collapseTransition>
        </a-row>
      </a-form>
      <a-form v-bind="$attrs" labelAlign="right" :form="form" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
        <a-row>
          <a-col :span="12">
            <a-form-item label="操作">
              <y-button type="primary" @click="handleSearch">查询</y-button>
              <y-button type="default" @click="handleReset">重置</y-button>
              <y-button
                :type="item.btType || 'primary'"
                v-show="moreHandles.length !== 0"
                v-for="(item, index) in moreHandles"
                :key="index"
                @click="moreHandle(item)"
                >{{ item.name }}</y-button
              >
              <slot name="action"></slot>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="serch-footer">
        <slot name="footer"></slot>
      </div>
      <a-tooltip placement="bottom" :mouseLeaveDelay="0">
        <div class="more" v-if="list.length > 2 * columnNum" @click="showMore = !showMore">
          {{ showMore ? '收起' : '展开' }}
        </div>
      </a-tooltip>
      <!-- <a-tooltip :title="showMore ? '收起' : '展开'" placement="bottom" :mouseLeaveDelay="0">
        <div class="more" v-if="list.length > 2 * columnNum" @click="showMore = !showMore">
          <a-icon :type="showMore ? 'caret-up' : 'caret-down'"> </a-icon>
        </div>
      </a-tooltip> -->
    </a-spin>
  </a-card>
</template>

<script>
/**
 * @Description：基于antd 封装的搜索框
 * @Version：1.0.3
 * @Date：2022-8-19 10:48:48
 * @LastEditors：Answer™
 * @LastEditTime：2022-9-30 09:16:44
 * @property：labelCol Object label占比
 * @property：wrapperCol Object wrappe占比
 * @property：columnNum Number 一行几个
 * @property more Boolean 默认是否展开更多
 * @property loading Boolean 加载状态
 * @property：list Array  搜索数组
 * {
 *  type: '' input | select | radio | check | week | month | date | year | range | switch
 *  label: '' 显示的label
 *  fields: '' 绑定字段名称
 *  extra： '' 提示文字
 *  validate: [] 表单验证
 *  initialValue: '' 默认值
 *  props: {} 组件参数
 *  methods: {} 组件事件
 * }
 * @slot header 顶部自定义
 * @slot footer 尾部自定义
 * @event：search 搜索事件
 * @event：reset 重置事件
 */
import { Input, Switch, Radio, Checkbox, Select, DatePicker, Cascader } from 'ant-design-vue'
import collapseTransition from './collapseTransition'
import yearPicker from '@/components/yearPicker'
import lodash from 'lodash'
import { postProposerExamineBatch } from '@/api/DistrictReviewReportManagement'
import moment from 'moment'
const { Group: checkboxGroup } = Checkbox
const { Group: RadioGroup } = Radio
const { MonthPicker, RangePicker, WeekPicker } = DatePicker
export default {
  components: {
    collapseTransition,
    yearPicker,
  },
  props: {
    // 自定义更多操作
    moreHandles: {
      type: Array,
      default: () => [],
    },
    labelCol: {
      type: Object,
      default: () => {
        return { span: 6 }
      },
    },
    wrapperCol: {
      type: Object,
      default: () => {
        return { span: 18 }
      },
    },
    columnNum: {
      type: Number,
      default: 3,
    },
    more: {
      type: Boolean,
      default: false,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array,
      default: () => [
        {
          label: '搜索名称', // 设置标签的label名
          fields: 'name', // value(Vmode)绑定的字段名
          type: 'input', // 设置标签类型为 input date select radio等
        },
      ],
    },
  },
  computed: {
    componentType() {
      return (type) => {
        const componentMap = new Map([
          ['INPUT', Input],
          ['SELECT', Select],
          ['SWITCH', Switch],
          ['CHECKBOX', checkboxGroup],
          ['DATE', DatePicker],
          ['RADIO', RadioGroup],
          ['MONTH', MonthPicker],
          ['WEEK', WeekPicker],
          ['RANGE', RangePicker],
          ['CASCADER', Cascader],
          ['YEAR', yearPicker],
        ])
        return componentMap.get(type.toLocaleUpperCase())
      }
    },
  },
  data() {
    return {
      form: this.$form.createForm(this),
      showMore: false,
    }
  },
  mounted() {
    this.showMore = this.more
  },
  methods: {
    // 更多操作
    moreHandle(item) {
      switch (item.name) {
        case '批量上报':
          if (this.$isEmpty(item.data)) {
            this.$message.warning('至少选择一条用户信息')
          } else {
            this.$confirm({
              title: '提示',
              content: `确定上报所选的${item.data.length}条用户信息吗？`,
              onOk: () => {
                this.$parent.$parent.$parent.$parent.$parent._data.spinning = true // 打开加载
                postProposerExamineBatch({
                  State: 'DistrictReport',
                  ProposerModules: {
                    ID: item.data.join(','),
                    SubmitToUser: this.$store.getters.nickname,
                    SubmitToDate: moment().format('YYYY-MM-DD HH:mm:ss'),
                    LastAlterDate: moment().format('YYYY-MM-DD HH:mm:ss'),
                    LastAlterUserID: this.$store.getters.userid,
                  },
                }).then((res) => {
                  this.$parent.$parent.$parent.$parent.$parent._data.spinning = false
                  this.$message.success('上报成功')
                  this.$parent.$parent.$parent.$parent.$parent.$refs.table.refresh()
                  // 清空传递多选的参数缓存
                  this.$parent.$parent.$parent.$parent.$parent._data.selectedRowKeys = []
                })
              },
            })
          }
          break
        case '批量接收':
          if (this.$isEmpty(item.data)) {
            this.$message.warning('至少选择一条用户信息')
          } else {
            this.$confirm({
              title: '提示',
              content: `确定接收所选的${item.data.length}条用户信息吗？`,
              onOk: () => {
                this.$parent.$parent.$parent.$parent.$parent._data.spinning = true // 打开加载
                postProposerExamineBatch({
                  State: 'CityReceive',
                  ProposerModules: {
                    ID: item.data.join(','),
                    ProcessUser: this.$store.getters.nickname,
                    ProcessDate: moment().format('YYYY-MM-DD HH:mm:ss'),
                    LastAlterDate: moment().format('YYYY-MM-DD HH:mm:ss'),
                    LastAlterUserID: this.$store.getters.userid,
                  },
                }).then((res) => {
                  this.$parent.$parent.$parent.$parent.$parent._data.spinning = false
                  this.$message.success('接收成功')
                  this.$parent.$parent.$parent.$parent.$parent.$refs.table.refresh()
                  // 清空传递多选的参数缓存
                  this.$parent.$parent.$parent.$parent.$parent._data.selectedRowKeys = []
                })
              },
            })
          }
          break
        case '通过所选':
          if (this.$isEmpty(item.data)) {
            this.$message.warning('至少选择一条用户信息')
          } else {
            this.$confirm({
              title: '提示',
              content: `确定接收所选的${item.data.length}条用户信息吗？`,
              onOk: () => {
                this.$parent.$parent.$parent.$parent.$parent._data.spinning = true // 打开加载
                postProposerExamineBatch({
                  State: 'CityRfyAudit',
                  ProposerModules: {
                    ID: item.data.join(','),
                    CityRfyAuditor: this.$store.getters.nickname,
                    CityRfyDate: moment(new Date()).format('YYYY-MM-DD'),
                    CityRfyResult: '符合',
                    LastAlterDate: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                    LastAlterUserID: this.$store.getters.userid,
                  },
                }).then((res) => {
                  this.$parent.$parent.$parent.$parent.$parent._data.spinning = false
                  this.$message.success('审批成功')
                  this.$parent.$parent.$parent.$parent.$parent.$refs.table.refresh()
                  // 清空传递多选的参数缓存
                  this.$parent.$parent.$parent.$parent.$parent._data.selectedRowKeys = []
                })
              },
            })
          }
          break
        case '不通过所选':
          if (this.$isEmpty(item.data)) {
            this.$message.warning('至少选择一条用户信息')
          } else {
            this.$confirm({
              title: '提示',
              content: `确定接收所选的${item.data.length}条用户信息吗？`,
              onOk: () => {
                this.$parent.$parent.$parent.$parent.$parent._data.spinning = true // 打开加载
                postProposerExamineBatch({
                  State: 'CityRfyAudit',
                  ProposerModules: {
                    ID: item.data.join(','),
                    CityRfyAuditor: this.$store.getters.nickname,
                    CityRfyDate: moment(new Date()).format('YYYY-MM-DD'),
                    CityRfyResult: '不符合',
                    LastAlterDate: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                    LastAlterUserID: this.$store.getters.userid,
                  },
                }).then((res) => {
                  this.$parent.$parent.$parent.$parent.$parent._data.spinning = false
                  this.$message.success('审批成功')
                  this.$parent.$parent.$parent.$parent.$parent.$refs.table.refresh()
                  // 清空传递多选的参数缓存
                  this.$parent.$parent.$parent.$parent.$parent._data.selectedRowKeys = []
                })
              },
            })
          }
          break
        case '通过全部':
          item.data().then((res) => {
            this.$confirm({
              title: '提示',
              content: `确定接收所选的${res.data.length}条用户信息吗？`,
              onOk: () => {
                this.$parent.$parent.$parent.$parent.$parent._data.spinning = true // 打开加载
                postProposerExamineBatch({
                  State: 'CityRfyAudit',
                  ProposerModules: {
                    ID: res.data.map((t) => t.ID).join(','),
                    CityRfyAuditor: this.$store.getters.nickname,
                    CityRfyDate: moment(new Date()).format('YYYY-MM-DD'),
                    CityRfyResult: '符合',
                    LastAlterDate: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                    LastAlterUserID: this.$store.getters.userid,
                  },
                }).then((res) => {
                  this.$parent.$parent.$parent.$parent.$parent._data.spinning = false
                  this.$message.success('审批成功')
                  this.$parent.$parent.$parent.$parent.$parent.$refs.table.refresh()
                  // 清空传递多选的参数缓存
                  this.$parent.$parent.$parent.$parent.$parent._data.selectedRowKeys = []
                })
              },
            })
          })
          break
      }
    },
    handleAllowClear(item) {
      const { type } = item
      if (type.toLocaleUpperCase() !== 'SELECT') {
        return false
      } else {
        if (item.props.hasOwnProperty('allowClear')) {
          return item.props.allowClear
        } else {
          return true
        }
      }
    },
    handleSearch() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$emit(
            'search',
            lodash.omitBy(values, (item) => !item)
          )
        }
      })
    },
    handleReset() {
      this.reset()
      this.$emit('reset', {})
    },
    // 获取值  手动获取搜索结果
    getFieldsValue(params) {
      return this.form.getFieldsValue(params)
    },
    // 重置数据
    setFieldsValue(params) {
      return this.form.setFieldsValue(params)
    },
    // 只重置表单 不触发向父级传递
    reset() {
      this.form.resetFields()
    },
  },
}
</script>
<style lang="less" scoped>
@import '~ant-design-vue/dist/antd.less';
.search-wrapper {
  position: relative;
  .more {
    position: absolute;
    bottom: -54px;
    left: 50%;
    transform: translateX(-50%);
    width: 200px;
    height: 30px;
    line-height: 20px;
    border-radius: 0px 0px 10px 10px;
    background-color: #fff;
    text-align: center;
    border: 1px solid color(~`colorPalette('@{primary-color}', 2) `);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    color: @primary-color;
    font-size: 20px;
    transition: all 0.3s;
    &:hover {
      font-size: 26px;
    }
  }
  .extra {
    color: color(~`colorPalette('@{warning-color}', 5) `);
    font-size: 12px;
  }
}
/deep/ .ant-form-item-label {
  white-space: normal;
  padding-right: 12px;
}
/deep/ .ant-calendar-picker {
  width: 100% !important;
}
</style>
